var core = require('core');
var sign = require('../sign');
var send = core.send;
var wechat = core.wechat;

var GET = function(req, res, next){
    var query = req.query;
    var token = query.token;
    var mid = query.mid;
    sign(token, function(doc){
        if(doc.code){
            doc.docs = {};
            req.error = doc;
            next();
        }else{
            core.api("merchant/find", {mid: mid}, function(err, doc){
                if(err){
                    req.error = new send(200000);
                    return next();
                }else if(doc.code){
                    req.error = doc;
                    return next();
                }else{
                    var SEND = new send(0);
                    // SEND.docs = {
                        // item : doc.docs,
                        // token : token,
                        // jssdk : wechat.getJSSDK(req.originalUrl)
                    // };
                    SEND.docs = doc.docs;
                    SEND.docs.token = token;
                    SEND.docs.jssdk = wechat.getJSSDK(req.originalUrl);
                    // res.send(SEND);
                    // console.log(SEND.docs)
                    res.render("admin/merchant_price", SEND);
                }
            });
        }

    });
};

var POST = function(req, res, next){
    var body = req.body;
    var token = body.token;
    var mid = body.mid;
    var price = body.price;
    sign(token, function(doc){
        if(doc.code){
            doc.docs = {};
            req.error = doc;
            next();
        }else{
            console.log({mid: mid, update: JSON.stringify({price: price.split("|")})});
            core.api("merchant/update", {mid: mid, update: JSON.stringify({price: price.split("|")})}, function(err, doc){
                if(err){
                    req.error = new send(200000);
                    return next();
                }else if(doc.code){
                    req.error = doc;
                    return next();
                }else{
                    res.send(doc);
                }
            });
        };
    });
};

exports.GET = GET;
exports.POST = POST;
